package org.example.java.nio.channels;

import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.concurrent.TimeUnit;

/**
 * Created by Juntao.Zhang on 2014/10/8.
 */
public class FlumeFileLock {
  public static final String FILE_LOCK = "in_use.lock";

  public static void main(String[] args) throws Exception {
    File checkpointDir = Files.createTempDir();
    checkpointDir.deleteOnExit();// lock.close() 之后就不起作用了
    File lockF = new File(checkpointDir, FILE_LOCK);
    lockF.deleteOnExit();
    FileLock lock = tryLock(checkpointDir);
    System.out.println("lock");
    TimeUnit.SECONDS.sleep(2);
    System.out.println(checkpointDir.toPath());
    System.out.println(lockF.toPath());
    lock.release();
    System.out.println("release");
    lock.channel().close();
  }


  private static FileLock tryLock(File dir) throws IOException {
    File lockF = new File(dir, FILE_LOCK);
    lockF.deleteOnExit();
    RandomAccessFile file = new RandomAccessFile(lockF, "rw");
    FileLock res = null;
    try {
      res = file.getChannel().tryLock();
    } catch (OverlappingFileLockException oe) {
      file.close();
      return null;
    } catch (IOException e) {
      System.err.printf("Cannot create lock on " + lockF, e);
      file.close();
      throw e;
    }
    return res;
  }
}
